<template>
  <div>
    <ConfigSetting id="data" ref="configSettingRef" v-model="dataForm"/>
    <ChartStyle id="style" ref="chartStyleRef" v-model="dataForm"/>
    <fixed-pagination>
      <div class="center">
        <el-button :loading="btnLoading" type="primary" size="small" @click="toSubmit">保存</el-button>
        <el-button class="cancel-btn-style" type="info" size="small" @click="handleClose">取消</el-button>
      </div>
      <div v-if="isEdit" class="foot-info">
        <div class="item">更新人：{{ dataForm.updateUserName || '--' }}</div>
        <div class="item">
          更新时间：
          <span v-if="dataForm.updateTime">{{ dataForm.updateTime | format('YYYY/MM/DD HH:mm') }}</span>
          <span v-else>--</span>
        </div>
      </div>
    </fixed-pagination>
  </div>
</template>

<script>
import ChartStyle from './chartStyle';
import ConfigSetting from './configSetting';
import { parseJson } from '@/utils';
import { createChartTable, editChartTable } from '@/api/reportManage';
import ElMessage from '@/utils/message';
import HandelParams from '../../mixins/handelParams';
import { format } from '@/filters/date';

export default {
  components: { ChartStyle, ConfigSetting },
  filters: { format },
  mixins: [HandelParams],
  props: {
    process: {
      type: Number,
      default: 0
    },
    tabId: {
      type: String | Number,
      default: ''
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    editType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      btnLoading: false,
      dataForm: {
        kind: 2,
        name: '',
        layout: '',
        layoutNum: 36,
        categoryId: '',
        isUpdateRegularly: false,
        showNums: undefined,
        styleConfig: '',
        updateRegularlyType: '1小时',
        selectField: [{ // selectField[0] 是关联字段，为必填
          columnName: '',
          fieldType: 0, // 0:普通字段  1:公式字段
          fieldName: '',
          fieldId: '',
          reportId: '',
          filedFormula: '',
          hideTag: 0,
          uniqueFlag: 1
        }],
        chartFilter: [{
          report: [],
          system: []
        }],
        isSplitChunk: false,
        chunkSeparator: '',
        isShow: true,
        sortShowType: 1,
        hasDataSource: false
      },
      defaultLayout: { x: 0, y: 0, h: 0 },
      defaultData: null
    };
  },
  mounted() {
    if (this.$refs.chartStyleRef) {
      this.$refs.chartStyleRef.getData();
    }
    this.defaultData = JSON.parse(JSON.stringify(this.dataForm));
  },
  methods: {
    setDefault(data) {
      this.setDefaultTime(data);
      this.dataForm = data;
      const layout = parseJson(data.layout);
      this.defaultLayout = layout;
      this.$set(this.dataForm, 'layoutNum', Number(layout.w || 12));
      if (this.$refs.configSettingRef) this.$refs.configSettingRef.setDefault(this.dataForm);
      if (this.$refs.chartStyleRef && this.dataForm.id) {
        this.$refs.chartStyleRef.setStyleDefault(this.dataForm.styleConfig);
      }
    },
    isDataChange() {
      if (this.$refs.chartStyleRef) {
        this.$refs.chartStyleRef.getData();
      }
      return JSON.stringify(this.dataForm) !== JSON.stringify(this.defaultData);
    },
    toSubmit() {
      const diyTableWidth = this.$refs.configSettingRef.handelParams();
      const dataForm = this.$refs.chartStyleRef.getData({ diyTableWidth });
      const error = this.handelFormulaField(dataForm);
      if (!dataForm.isOrder) {
        dataForm.sortField = '';
        dataForm.sortType = '';
        dataForm.showNums = '';
      }
      if (error && error.msg) {
        ElMessage.error(error.msg);
        return;
      }
      if (dataForm.isSplitChunk && !dataForm.chunkSeparator) {
        ElMessage.error('请输入拆分标识');
        return;
      }
      this.handelChartFilter(dataForm);
      const validatePromise = [];
      validatePromise.push(this.$refs.configSettingRef.validate());
      Promise.all(validatePromise).then(() => {
        const layout = this.defaultLayout;
        layout.w = dataForm.layoutNum;
        dataForm.layout = JSON.stringify(layout);
        dataForm.tabId = this.tabId;
        if (dataForm.selectField) {
          dataForm.linkDataSheet = [];
          dataForm.selectField.forEach((i, index) => {
            if (i.sourceId) {
              if (index === 0) {
                dataForm.dataSheet = i.sourceId;
              } else {
                dataForm.linkDataSheet.push(i.sourceId);
              }
            }
          });
        }
        dataForm.isMobile = this.$route.query.editMobileMode ? 1 : 0;
        if (!this.isEdit || this.editType === 'copy') {
          this.add(dataForm);
        } else {
          this.edit(dataForm);
        }
      }).catch(err => {
        console.log(err);
        this.$message.error('请检查信息是否填写完整');
      });
    },
    add(dataForm) {
      this.btnLoading = true;
      createChartTable(dataForm).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message.success('新增成功');
          this.handleClose();
        } else {
          this.$message.error(res.message);
        }
      }).catch(err => {
        this.btnLoading = false;
        console.log(err);
        // this.$message.error(err.message);
      });
    },
    edit(dataForm) {
      this.btnLoading = true;
      dataForm.id = this.$route.params.id || '';
      editChartTable(dataForm).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message.success('编辑成功');
          this.handleClose();
        } else {
          this.$message.error(res.message);
        }
      }).catch(err => {
        this.btnLoading = false;
        console.log(err);
        // this.$message.error(err.message);
      });
    },
    // 处理公式字段
    handelFormulaField(dataForm) {
      const repeatName = [];
      let error = '';
      dataForm.selectField.forEach((i, index) => {
        if (index === 0) {
          i.uniqueFlag = 1;
        }
        if (i.fieldType === 1) {
          i.fieldName = i.columnName;
          let tagFormula = '';
          const formulaVariable = [];
          if (i.formulaOrigin && i.formulaOrigin.length > 0) {
            i.formulaOrigin.forEach(j => {
              if (j.type === 'var') {
                const varObj = {
                  name: j.fieldName,
                  fieldName: j.fieldName,
                  columnName: j.columnName,
                  fieldId: j.fieldId
                };
                formulaVariable.push(varObj);
                tagFormula = tagFormula + '#' + j.columnName + '#';
              } else {
                tagFormula = tagFormula + j.tagName;
              }
              const notDelete = ['fieldName', 'fieldId', 'type', 'name', 'columnName', 'tagName'];
              for (const key in j) {
                if (!notDelete.includes(key)) {
                  delete j[key];
                }
              }
            });
          }
          i.formulaVariable = formulaVariable; // 公式中的变量
          i.tagFormula = tagFormula; // 公式
          i.formulaOrigin = i.formulaOrigin ? JSON.stringify(i.formulaOrigin) : '';
        } else {
          i.formulaOrigin = '';
        }

        if (repeatName.includes(i.columnName)) {
          error = '列名称不能重复';
        }
        if (!i.columnName) {
          error = '选取字段中列名称未填写';
        } else {
          repeatName.push(i.columnName);
        }
      });
      if (!dataForm.selectField || dataForm.selectField.length === 0 || dataForm.selectField[0].fieldName === '') {
        error = '请选取关联字段';
      }
      return { msg: error };
    },
    handleClose() {
      this.$emit('goBack');
    },
    switchProcess({ id }) {
      this.$emit('switchProcess', { id });
    }
  }
};
</script>

<style lang="scss" scoped>
.foot-info {
  display: flex;
  align-items: center;
  position: absolute;
  right: 10px;
  .item {
    flex-shrink: 0;
    margin-left: 10px;
    color: #999;
  }
}
</style>
